package com.webserver6.controllor;

import com.webserver6.annotations.Controller;
import com.webserver6.annotations.RequestMapping;
import com.webserver6.http.HttpServletResponse;
import com.webserver6.http.HttpServletRequest;
import com.webserver6.util.DBUtil;

import java.sql.*;

@Controller
public class ArticleController {
    @RequestMapping("/writeArticle")
    public void write(HttpServletRequest request , HttpServletResponse response){
        System.out.println("开始处理发表文章功能！！！");
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        String content = request.getParameter("content");
        try(
                Connection connection = DBUtil.getConnection();
                ) {
            String sql = "SELECT id FROM userinfo WHERE username=?";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1,author);
            ResultSet rs = ps.executeQuery();
            if (rs.next()){
                int id = rs.getInt("id");
                sql = "INSERT INTO article (title,content,u_id) VALUES (?,?,?)";
                ps=connection.prepareStatement(sql);
                ps.setString(1,title);
                ps.setString(2,content);
                ps.setInt(3,id);
                int num = ps.executeUpdate();
                if (num>0){
                    response.sendRedirect("/write_article_success.html");
                }else {
                    response.sendRedirect("/write_article_fail.html");
                }
            }else {
                response.sendRedirect("/have_not_user.html");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
